package com.kakarote.oa.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kakarote.common.log.annotation.OperateLog;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.entity.OperationResult;
import com.kakarote.common.log.enums.ApplyEnum;
import com.kakarote.common.log.enums.BehaviorEnum;
import com.kakarote.common.log.enums.OperateObjectEnum;
import com.kakarote.common.log.enums.OperateTypeEnum;
import com.kakarote.core.common.Result;
import com.kakarote.core.common.cache.CrmCacheKey;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.servlet.LoginFromCookie;
import com.kakarote.core.utils.BaseUtil;
import com.kakarote.oa.entity.BO.OaPrintTemplateQueryBO;
import com.kakarote.oa.entity.PO.OaLogPrintTemplate;
import com.kakarote.oa.entity.VO.OaLogTemplateFieldVO;
import com.kakarote.oa.service.IOaLogPrintTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.util.List;

/**
 * @author wwl
 * @date 2022/7/7 9:19
 */
@RestController
@RequestMapping("/oaLogPrintTemplate")
@Slf4j
@Api(tags = "日志打印模板")
public class OaLogPrintTemplateController {

    @Autowired
    private IOaLogPrintTemplateService oaLogPrintTemplateService;

    @ApiOperation("查询打印模板列表")
    @PostMapping("/queryList")
    public Result<BasePage<OaLogPrintTemplate>> queryList(@RequestBody OaPrintTemplateQueryBO printTemplateBO) {
        BasePage<OaLogPrintTemplate> adminPrintTemplateBasePage = oaLogPrintTemplateService.queryList(printTemplateBO);
        return Result.ok(adminPrintTemplateBasePage);
    }

    @ApiOperation("新增模板")
    @PostMapping("/add")
    @OperateLog(apply = ApplyEnum.OFFICE_MANAGEMENT, behavior = BehaviorEnum.SAVE, object = OperateObjectEnum.LOG_PRINT_TEMPLATE, type = OperateTypeEnum.SETTING)
    public Result addPrintTemplate(@RequestBody OaLogPrintTemplate template) {
        OperationLog operationLog = oaLogPrintTemplateService.add(template);
        return OperationResult.ok(operationLog);
    }

    @ApiOperation("修改模板")
    @PostMapping("/update")
    @OperateLog(apply = ApplyEnum.OFFICE_MANAGEMENT, behavior = BehaviorEnum.UPDATE, object = OperateObjectEnum.LOG_PRINT_TEMPLATE, type = OperateTypeEnum.SETTING)
    public Result updatePrintTemplate(@RequestBody OaLogPrintTemplate adminPrintTemplate) {

        OaLogPrintTemplate template = oaLogPrintTemplateService.getById(adminPrintTemplate.getTemplateId());

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(template.getTemplateName());
        operationLog.setOperationInfo("编辑日志打印模板：" + template.getTemplateName());

        oaLogPrintTemplateService.updateById(adminPrintTemplate);
        return OperationResult.ok(operationLog);
    }

    @ApiOperation("跟进ID查询打印模板")
    @PostMapping("/queryById")
    public Result<OaLogPrintTemplate> queryPrintTemplateById(@RequestParam("templateId") Long templateId) {
        OaLogPrintTemplate byId = oaLogPrintTemplateService.getById(templateId);
        return Result.ok(byId);
    }

    @ApiOperation("删除模板")
    @PostMapping("/delete")
    @OperateLog(apply = ApplyEnum.OFFICE_MANAGEMENT, behavior = BehaviorEnum.DELETE, object = OperateObjectEnum.LOG_PRINT_TEMPLATE, type = OperateTypeEnum.SETTING)
    public Result deletePrintTemplate(@RequestParam("templateId") Long templateId) {
        OperationLog operationLog = oaLogPrintTemplateService.deletePrintTemplate(templateId);
        return OperationResult.ok(operationLog);
    }

    @ApiOperation("查询字段")
    @PostMapping("/queryFields")
    public Result<List<OaLogTemplateFieldVO>> queryFields(@RequestParam("logTemplateId") Long logTemplateId) {
        List<OaLogTemplateFieldVO> voList = oaLogPrintTemplateService.queryFields(logTemplateId);
        return Result.ok(voList);
    }

    @ApiOperation("打印")
    @PostMapping("/print")
    public Result<String> print(@RequestParam("templateId") Long templateId, @RequestParam("id") Long id) {
        String print = oaLogPrintTemplateService.print(templateId, id);
        return Result.ok(print);
    }

    @ApiOperation("预览")
    @PostMapping("/preview")
    public Result<String> preview(@RequestParam("content") String content, @RequestParam("type") String type) {
        String s = oaLogPrintTemplateService.preview(content, type, null);
        return Result.ok(s);
    }

    @ApiOperation("iframe")
    @RequestMapping("/preview.pdf")
    @LoginFromCookie
    public void preview(String key, HttpServletResponse response) {
        String object = BaseUtil.getRedis().get(CrmCacheKey.CRM_PRINT_TEMPLATE_CACHE_KEY + key);
        if (StrUtil.isNotEmpty(object)) {
            JSONObject parse = JSON.parseObject(object);
            String path = parse.getString("pdf");
            if (FileUtil.exist(path)) {
                File file = FileUtil.file(path);
                BufferedInputStream in = null;
                ServletOutputStream out = null;
                try {
                    in = FileUtil.getInputStream(file);
                    response.setContentType("application/pdf");
                    IoUtil.copy(in, response.getOutputStream());
                } catch (Exception ex) {
                    log.error("导出错误", ex);
                } finally {
                    IoUtil.close(in);
                    IoUtil.close(out);
                }
                return;
            }
        }
        ServletUtil.write(response, Result.ok().toJSONString(), "text/plain");
    }

    @ApiOperation("下载文件")
    @RequestMapping("/down")
    @LoginFromCookie
    public void down(@RequestParam("type") Integer type, @RequestParam("key") String key, HttpServletResponse response) {
        String object = BaseUtil.getRedis().get(CrmCacheKey.CRM_PRINT_TEMPLATE_CACHE_KEY + key);
        if (StrUtil.isNotEmpty(object)) {
            JSONObject parse = JSON.parseObject(object);
            String path;
            int two = 2;
            if (type == two) {
                path = parse.getString("word");
            } else {
                path = parse.getString("pdf");
            }
            if (FileUtil.exist(path)) {
                ServletUtil.write(response, FileUtil.file(path));
                return;
            }
        }
        ServletUtil.write(response, Result.ok().toJSONString(), "text/plain");
    }

    @ApiOperation("复制模板")
    @PostMapping("/copyTemplate")
    @OperateLog(apply = ApplyEnum.OFFICE_MANAGEMENT, behavior = BehaviorEnum.COPY, object = OperateObjectEnum.LOG_PRINT_TEMPLATE, type = OperateTypeEnum.SETTING)
    public Result copyTemplate(@RequestParam("templateId") Long templateId) {
        OperationLog operationLog = oaLogPrintTemplateService.copyTemplate(templateId);
        return OperationResult.ok(operationLog);
    }

}
